#pragma once

#include <iostream>
#include <string>
#include <unordered_map>

#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

using namespace std;

class User
{
public:
    User(const string &ip, uint16_t &port)
        : _ip(ip), _port(port)
    {
    }
    ~User()
    {
    }

public:
    string _ip;
    uint16_t _port;
};

class onlineUser
{
public:
    onlineUser()
    {
    }
    
    ~onlineUser()
    {
    }

    void addUser(const string &ip, uint16_t &port)
    {
        string id = ip + " - " + to_string(port);
        _users.insert(make_pair(id, User(ip, port)));
    }

    void delUser(const string &ip, uint16_t &port)
    {
        string id = ip + " - " + to_string(port);
        _users.erase(id);
    }

    bool isOnline(const string &ip, uint16_t &port)
    {
        string id = ip + " - " + to_string(port);
        return _users.find(id) == _users.end() ? false : true;
    }

    void routeMsg(int sockfd, const string &ip, uint16_t &port, string &messages)
    {
        for (auto &user : _users)
        {
            struct sockaddr_in client;
            bzero(&client, 0);

            client.sin_family = AF_INET;
            client.sin_port = htons(user.second._port);
            client.sin_addr.s_addr = inet_addr(user.second._ip.c_str());

            string s = ip + "[" + to_string(port) + "] ";
            s += messages;
            sendto(sockfd, s.c_str(), s.size(), 0, (struct sockaddr *)&client, sizeof(client));
        }
    }

    void sendtoOne(int sockfd, const string &ip, uint16_t &port, string &messages)
    {
        struct sockaddr_in client;
        bzero(&client, 0);

        client.sin_family = AF_INET;
        client.sin_port = htons(port);
        client.sin_addr.s_addr = inet_addr(ip.c_str());

        sendto(sockfd, messages.c_str(), messages.size(), 0, (struct sockaddr *)&client, sizeof(client));
    }

private:
    unordered_map<string, User> _users;
};